<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.keyword" placeholder="请输入关键字" style="width: 200px;" clearable class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-select v-model="listQuery.is_pass" placeholder="状态" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in isPassOptions" :key="item.key" :label="item.name" :value="item.key"/>
      </el-select>
      <el-select v-model="listQuery.payment_type" placeholder="支付方式" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in paymentTypeOptions" :key="item.key" :label="item.name" :value="item.key"/>
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key"/>
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">新增</el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
      <!--<el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">{{ $t('table.reviewer') }}</el-checkbox>-->
    </div>
    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange">
      <el-table-column label="序号" prop="id" sortable="custom" align="center" width="65">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" min-width="150px">
        <template slot-scope="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类" width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.category ? scope.row.category.name : "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="点赞数" width="80px" align="center">
        <template slot-scope="scope">
          <span >{{ scope.row.support }}</span>
        </template>
      </el-table-column>
      <el-table-column label="吐槽数" width="80px" align="center">
        <template slot-scope="scope">
          <span >{{ scope.row.oppose }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时长" width="80px" align="center">
        <template slot-scope="scope">
          <span >{{ scope.row.play_time }} sec</span>
        </template>
      </el-table-column>
      <el-table-column label="等级" width="80px" align="center">
        <template slot-scope="scope">
          <span >{{ scope.row.level }}</span>
        </template>
      </el-table-column>
      <el-table-column label="价格" width="80px" align="center">
        <template slot-scope="scope">
          <span >{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" width="80px" align="center">
        <template slot-scope="scope">
          <span >{{ scope.row.payment_type | payTypeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="观看数" width="80px" align="center">
        <template slot-scope="scope">
          <span >{{ scope.row.num }}人</span>
        </template>
      </el-table-column>
      <el-table-column label="aaa" align="center" width="95">
        <template slot-scope="scope">
          <span v-if="scope.row.support" class="link-type" @click="handleFetchPv(scope.row.support)">{{ scope.row.support }}</span>
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="80px" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_pass | statusClassFilter">{{ scope.row.is_pass | statusFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.update_time | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button v-if="scope.row.is_pass=='0'" size="mini" type="primary" @click="handleModifyStatus(scope.row,'is_pass')">通过
          </el-button>
          <el-button v-if="scope.row.is_pass=='0'" size="mini" type="primary" @click="handleModifyStatus(scope.row,'')">不通过
          </el-button>
          <el-button v-if="scope.row.is_pass=='1'" size="mini" type="success" @click="handleModifyStatus(scope.row,'rm_pass')">撤销
          </el-button>
          <el-button v-if="scope.row.is_pass=='-1'" size="mini" type="warning" @click="handleModifyStatus(scope.row,'re_pass')">重审
          </el-button>
          <el-button v-if="scope.row.status!='deleted'" size="mini" type="danger" @click="handleModifyStatus(scope.row,'deleted')">{{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="名称" prop="name" >
          <el-input v-model="temp.name" placeholder="请输入视频名称" clearable/>
        </el-form-item>
        <el-form-item label="付费类型">
          <el-select v-model="temp.payment_type" class="filter-item" placeholder="请选择付费类型" clearable>
            <el-option v-for="item in paymentTypeOptions" :key="item.key" :label="item.name" :value="item.key"/>
          </el-select>
        </el-form-item>
        <el-form-item label="等级">
          <el-select v-model="temp.level" clearable>
            <el-option v-for="item in levelList" :label="item.name" :key="item.key" :value="item.key" placeholder="请选择等级" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间" >
          <el-date-picker v-model="temp.timestamp" type="datetime" placeholder="请选择时间" clearable/>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="temp.is_pass" class="filter-item" placeholder="请选择" clearable>
            <el-option v-for="item in isPassOptions" :key="item.key" :label="item.name" :value="item.key"/>
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="rootCategoryId" class="filter-item" placeholder="请选择" clearable>
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
          <el-select v-model="temp.category_id" class="filter-item" placeholder="请选择" clearable>
            <el-option v-for="item in categoryChildren" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item v-show="priceInputShow" label="价格" >
          <el-input-number v-model="temp.price" :step="0.5" :precision="2" size="1" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="关键字">
          <el-input v-model="temp.keyword" type="textarea" placeholder="请输入关键字"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button :disabled="isDisabled" type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel"/>
        <el-table-column prop="pv" label="Pv"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getVideoList, addVideo, getVideoInfo, updateVideo, updateVideoStatus } from '@/api/video'
import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'
import { getClassesCategory } from '@/api/classes'
import Pagination from '@/components/Pagination'
const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})
export default {
  name: 'VideoList',
  components: {
    Pagination
  },
  directives: {
    waves
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '1': '已审核',
        '-1': '未通过',
        '0': '待审核'
      }
      return statusMap[status]
    },
    statusClassFilter(status) {
      const statusClass = {
        '1': 'success',
        '-1': 'danger',
        '0': 'info'
      }
      return statusClass[status]
    },
    payTypeFilter(type) {
      const payStatus = {
        '0': '免费',
        '1': '金币',
        '2': '人民币'
      }
      return payStatus[type]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      isDisabled: false,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        payment_type: '',
        is_pass: '',
        importance: undefined,
        keyword: undefined,
        type: undefined,
        sort: 'id'
      },
      categoryList: [], // 分类根目录
      categoryChildren: [], //
      rootCategoryId: undefined,
      paymentTypeOptions: [
        { key: '0', name: '免费' },
        { key: '1', name: '金币' },
        { key: '2', name: '人民币' }
      ],
      isPassOptions: [
        { key: 0, name: '待审核' },
        { key: 1, name: '已审核' },
        { key: -1, name: '未通过' }
      ],
      levelList: [
        { key: 0, name: '中职' },
        { key: 1, name: '高职' },
        { key: 2, name: '本科' }
      ],
      calendarTypeOptions: [
        { key: 'CN', display_name: 'China' },
        { key: 'US', display_name: 'USA' },
        { key: 'JP', display_name: 'Japan' },
        { key: 'EU', display_name: 'Eurozone' }
      ],
      sortOptions: [{ label: 'ID 升序', key: 'id' }, { label: 'ID 降序', key: '-id' }],
      // statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      priceInputShow: true, // 是否显示价格文本框
      // 初始值
      temp: {
        id: undefined,
        user_id: undefined,
        name: '',
        timestamp: new Date(),
        keyword: '',
        category_id: undefined,
        url: '',
        play_time: '',
        level: '',
        price: 0,
        payment_type: '',
        is_share: '',
        is_delete: '',
        is_pass: '',
        num: '',
        update_time: new Date()
      },
      dialogFormVisible: false, // 默认模态框是不显示的
      dialogStatus: '', // 模态框的状态 是新增还是编辑
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '名称是必填项', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false

    }
  },
  watch: {
    rootCategoryId(val) { // 监听父分类的id
      this.getClassesCategoryRoot(val, 1)
    },
    'temp.payment_type': function(val) {
      if (val === '0') {
        this.priceInputShow = false
      } else {
        this.priceInputShow = true
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getClassesCategoryRoot(pid, isRoot) {
      if (isRoot === 0) {
        return getClassesCategory(pid).then(res => {
          this.categoryList = res.data.data
        }).catch(error => {
          console.log(error)
        })
      } else if (isRoot === 1) {
        return getClassesCategory(pid).then(res => {
          this.categoryChildren = res.data.data
        }).catch(error => {
          console.log(error)
        })
      }
    },
    getList() { // 获取列表数据
      // 加载load动画
      this.listLoading = true
      getVideoList(this.listQuery).then(res => {
        const result = res.data
        const pageInfo = result.meta
        this.list = result.data
        this.total = pageInfo.total
        console.log(result)
      }).catch(err => {
        console.log(err.message)
      })
      setTimeout(() => {
        this.listLoading = false
      }, 1000)
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    // 设置分页导航事件
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      if (status === 'deleted') {
        this.$confirm('该操作将删除视频，是否继续', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const deleteData = { 'id': row.id, 'type': 'delete', 'status': 1 }
          updateVideoStatus(deleteData).then((res) => {
            console.log(res)
            // const rowIndex = this.list.indexOf(row)
            this.getList()
            // this.list.splice(rowIndex, 1)
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          }).catch(err => {
            console.log(err)
            this.$message({
              message: '操作失败',
              type: 'error'
            })
          })
        })
      } else {
        this.$confirm('您确认要进行此操作吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let isPass
          if (status === 'is_pass') {
            isPass = 1
          } else if (status === 'rm_pass') {
            isPass = 0
          } else if (status === 're_pass') {
            isPass = 1
          } else {
            isPass = -1
          }
          const currentIndex = this.list.indexOf(row)
          const passData = { 'id': row.id, 'type': 'is_pass', 'status': isPass }
          updateVideoStatus(passData).then((res) => {
            this.list[currentIndex].is_pass = isPass
            console.log(res)
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          }).catch(err => {
            console.log(err)
            this.$message({
              message: '操作失败',
              type: 'error'
            })
          })
        })
        row.status = status
      }
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = 'id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        user_id: 1,
        name: '',
        timestamp: new Date(),
        keyword: '',
        type: 'published',
        category_id: '',
        url: '',
        play_time: '',
        level: '',
        price: '',
        payment_type: '',
        is_share: '',
        is_delete: '',
        is_pass: '',
        num: '',
        update_time: new Date()

      }
    },
    handleCreate() {
      this.resetTemp()
      this.categoryList = this.getClassesCategoryRoot(0, 0)
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024
          addVideo(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          }).catch(err => {
            this.$notify({
              title: '提示',
              message: err.message,
              type: 'error',
              duration: 1000
            })
          })
        }
      })
    },
    // 点击标题 弹出模态框修改
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // 复制保存当前这一行数据
      if (row.price === 0) {
        this.priceInputShow = false
      } else {
        this.priceInputShow = true
      }
      this.isDisabled = false // 设置提交按钮可用
      this.getClassesCategoryRoot(0, 0)
      this.categoryChildren = this.getClassesCategoryRoot(row.category.parent_id, 1)
      this.rootCategoryId = row.category.parent_id // 给父分类id
      this.temp.category_id = row.category.id // 给父分类id
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update' //  编辑状态
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.temp.category_id = row.category.id // 给父分类id
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.isDisabled = true
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateVideo(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp) // 替换之前data list中 修改后的数据
                break
              }
            }
            this.dialogFormVisible = false
            this.$message({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          }).catch(err => {
            this.$message({
              title: '验证失败',
              message: err.message,
              type: 'error',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      getVideoInfo(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    // 下载excel
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>

<style scoped>

</style>
